package com.hontech.libratest.app

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import kotlinx.coroutines.CompletableDeferred


class HandlerThread2(name: String) : HandlerThread(name) {

    init {
        start()
    }
}

object AppTask : Handler(Looper.getMainLooper())

object ConnTask : Handler(HandlerThread2("connTask").looper)

private class PromiseTask<T>(val cb: () -> T) : Runnable {

    private val promise = CompletableDeferred<T>()

    suspend fun await() = promise.await()

    override fun run() {
        try {
            val r = cb()
            promise.complete(r)
        } catch (e: Exception) {
            promise.completeExceptionally(e)
        }
    }
}



suspend fun <T> runAsync(cb: () -> T): T {
    val task = PromiseTask(cb)
    ConnTask.post(task)
    return task.await()
}


